package com.zhiwang.planet.mvp.p

import android.os.Environment
import android.util.Log
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.util.FormatUtil
import com.zhiwang.planet.util.androidSchedule
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@ActivityScope
class UtilPresenter @Inject constructor(var restApi: RestApi) {


    interface CallBack {
        fun onDownLoadComplete(f: File)
    }

    /**
     * 仅限于快速下载单张图片或者小文件
     */
    fun downLoadFile(url: String, cb: CallBack, downloadFileName: String? = null) {
        var subscribe = restApi.downloadFile(url)
                .androidSchedule()
                .map {
                    val stream = it.byteStream()
                    val fileHeader = ByteArray(8)
                    stream.read(fileHeader)

                    val format = FormatUtil.getImageFormat(fileHeader)
                    val fileName =
                            if (downloadFileName == null)
                                SimpleDateFormat.getTimeInstance().format(Date()).plus(".$format")
                            else downloadFileName.plus(".$format")
                    val filePath = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "趣味星球" + File.separator + fileName)
                    if (filePath.parentFile.exists().not()) filePath.parentFile.mkdirs()
                    if (filePath.exists().not()) filePath.createNewFile()
                    val bufFos = BufferedOutputStream(FileOutputStream(filePath))
                    val buffer = ByteArray(4096)
                    var byteRead = -1
                    bufFos.write(fileHeader)
                    while (stream.read(buffer).also { byteRead = it } != -1) {
                        bufFos.write(buffer, 0, byteRead)
                        bufFos.flush()
                    }
                    bufFos.close()
                    stream.close()
                    return@map filePath
                }.subscribe({
                    cb.onDownLoadComplete(it)
                }, {
                    Log.i("UtilPresenter", it.message)
                })
    }
}